<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <!-- 左侧 -->
          <el-tab-pane label="角色管理" name="role">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="showAddRoleDialog"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="loading" :data="list">
              <el-table-column
                type="index"
                label="序号"
                width="100"
                :index="indexMethod"
              />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="showAssignDialogFn(row.id)">分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="showEditRoleDialog(row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <!--
                属性:
                  1. current-page 标记当前页 (谁高亮)
                  2. page-sizes 可供选择的每页条数列表
                  3. page-size 起作用的每页条数
                  4. layout 布局, 控制是展示的控件列表布局
                  5. total 总条数
                方法:
                  @size-change="handleSizeChange" 每页条数变化
                  @current-change="handleCurrentChange" 当前页变化
              -->
            <div
              style="padding: 10px; display: flex; justify-content: flex-end"
            >
              <el-pagination
                :current-page="page"
                :page-sizes="[1, 2, 3, 4, 5]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="公司信息" name="company">
            <!-- 公司信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="showTitle" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog">
        <el-form
          ref="roleForm"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handleAddRole">确认</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" :close-on-click-modal="false" @close="closeAssignDialog" @open="openAssignDialog">
        <el-tree
          ref="tree"
          v-loading="loading"
          :data="permissionData"
          :props="{label:'name'}"
          :check-strictly="true"
          :show-checkbox="true"
          :default-expand-all="true"
          node-key="id"
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click=" editRolePermission">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getRoleListApi,
  deleteRoleApi,
  addRoleApi,
  getRoleDetailApi,
  editRoleApi
} from '@/api/setting'
import { getCompanyByIdApi } from '@/api/company'
import { mapState } from 'vuex'
import { getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import { assignPermApi } from '@/api/setting'
export default {
  name: 'Setting',
  data() {
    return {
      page: 1,
      pagesize: 2,
      list: [],
      total: 0,
      loading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: ['blur', 'change']
          }
        ],
        description: [
          {
            required: true,
            message: '请输入角描述',
            trigger: ['blur', 'change']
          }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      activeName: 'role',
      // 权限列表
      permissionData: [],
      // 控制分配权限的弹框
      showAssignDialog: false,
      // 分配权限的id
      roleId: '',
      // 角色已有的权限
      permIds: []

    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  watch: {
    activeName(newVal) {
      if (newVal === 'company') {
        this.getCompanyInfo()
      }
    }
  },
  created() {
    this.getRoleList() // 获取角色列表
    this.getCompanyInfo() // 获取公司信息(也可以通过监听属性获取)
  },
  methods: {
    async getRoleList() {
      // 请求拿到数据之前loading效果
      this.loading = true
      const { data } = await getRoleListApi(this.page, this.pagesize)
      const { total, rows } = data
      this.total = total
      this.list = rows
      // 请求拿到数据后关闭loading效果
      this.loading = false
    },
    // 修改了每页条数后, 会造成页数的变化, 推荐从第一页重新开始展示
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 更新每页条数
      this.pagesize = val
      // 重置当前页
      this.page = 1
      // 调用方法, 重新请求
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // 更新当前页
      this.page = val
      // 调用方法, 重新请求渲染
      this.getRoleList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    delRole(id) {
      this.$confirm('确认要删除该角色吗?', '温馨提示')
        .then(async() => {
          await deleteRoleApi(id) // 调用删除接口
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.getRoleList() // 删除后重新加载数据
          this.$$message.success('删除角色成功')
        })
        .catch((error) => {
          console.log(error)
        })
    },
    /**
     * 展示弹框、
     */
    showAddRoleDialog() {
      this.showDialog = true
      this.form = {
        name: '',
        description: ''
      }
    },
    closeDialog() {
      this.showDialog = false
      // 重置表单数据
      this.$refs.roleForm.resetFields()
    },
    handleAddRole() {
      this.$refs.roleForm.validate(async(flag) => {
        if (!flag) return
        // 后台的接口数据中修改和新增区别是有无id值，修改有id，新增无id；通过id值有无判断是修改逻辑还是新增逻辑
        if (this.form.id) {
          await editRoleApi(this.form)
          this.$message.success('恭喜!修改成功')
        } else {
          await addRoleApi(this.form)
          this.$message.success('恭喜!添加成功')
        }
        // 关闭弹窗
        this.closeDialog()
        // 刷新页面数据
        this.getRoleList()
      })
    },
    /**
     * 展示修改弹框
     * @param {*} id
     */
    async showEditRoleDialog(id) {
      this.showDialog = true
      const { data } = await getRoleDetailApi(id)
      // 让数据回显到表单中
      this.form = data
    },
    /**
     * 获取公司信息
     */
    async getCompanyInfo() {
      const { data } = await getCompanyByIdApi(this.userInfo.companyId)
      this.companyForm = data
    },
    /**
     * 打开分配权限弹框
     */
    showAssignDialogFn(id) {
      this.showAssignDialog = true
      this.roleId = id
      // console.log(this.roleId)
    },
    /**
     * 打开分配权限弹框后调用的函数
     */
    async openAssignDialog() {
      this.loading = true
      // 获取所有的权限列表
      this.getPermissionList()
      // 获取当前角色已有的权限
      const { data } = await getRoleDetailApi(this.roleId)
      // console.log(data)
      this.permIds = data.permIds
      this.$refs.tree.setCheckedKeys(this.permIds)
      // console.log(this.permIds)
      this.loading = false
    },
    /**
     *  关闭分配权限的弹框
     */
    closeAssignDialog() {
      this.showAssignDialog = false
      this.$refs.tree.setCheckedKeys([])
    },
    /**
     * 获取所有权限列表
     */
    async getPermissionList() {
      // 获取权限列表接口
      const { data } = await getPermissionListApi()
      // console.log(data)
      this.permissionData = transListToTreeData(data, '0')
      // console.log(this.permissionData)
    },
    // 点击确认，给角色分配权限
    async editRolePermission() {
      // console.log(this.roleId)
      // console.log(this.$refs.tree.getCheckedKeys())
      const checkPermIds = this.$refs.tree.getCheckedKeys()
      await assignPermApi({ id: this.roleId, permIds: checkPermIds })
      this.$message.success('分配成功')
      this.showAssignDialog = false
    }
  }
}
</script>

<style>
</style>
